#coding:utf-8
from lovewith.website.models import Province, City
from lovewith.utils.mtcache import MtCache


class ProvinceApi:
    def __init__(self):
        pass

    @staticmethod
    def check_data(pid=None, cid=None):
        country_filter_data = None
        if pid:
            country_filter_data = Province.objects.filter(id=int(pid))
        elif cid:
            country_filter_data = City.objects.filter(id=int(cid))

        if country_filter_data and country_filter_data.exists():
            return country_filter_data[0]
        else:
            return None


    @staticmethod
    def check_by_name(province_name=None, city_name=None):
        country_filter_data = None
        if province_name:
            country_filter_data = Province.objects.filter(name=province_name)
        if city_name:
            country_filter_data = City.objects.filter(name=city_name)

        if country_filter_data and country_filter_data.exists():
            return country_filter_data[0]

        return None


    #获取全部连接
    @staticmethod
    def get_all():
        country_data = MtCache('province_city').get()

        if not country_data:
            country_data = []
            province_data = Province.objects.all().order_by('id')
            for p in province_data:
                citys = []
                city_data = City.objects.filter(province_id=p.id).order_by('id')
                for c in city_data:
                    citys.append({
                        'id': c.id,
                        'name': c.name
                    })

                country_data.append({
                    'id': p.id,
                    'name': p.name,
                    'citys': citys
                })

            MtCache('province_city').set(country_data)

        return country_data